import { createRouter, createWebHashHistory, createWebHistory } from 'vue-router'
import NProgress from 'nprogress'
import utils from '@/utils/index'

// 在 Vue-router新版本中，需要使用createRouter来创建路由
const Router = createRouter({
  // 指定路由的模式,此处使用的是hash模式
  // history: createWebHashHistory(),
  history: createWebHistory(),
  // 路由地址
  routes: [{
    path: '/',
    meta: {
      auth: true,
      title: '你好！欢迎'
    },
    name: 'home',
    component: () => import('../views/Home.vue')
  }, {
    path: '/page1',
    meta: {
      auth: true,
      keepAlive: true,
      title: '测试页1'
    },
    name: 'page1',
    component: () => import('../views/Page1.vue')
  }, {
    path: '/page3',
    meta: {
      auth: true,
      title: '测试页3'
    },
    name: 'page3',
    component: () => import('../views/Page3.vue')
  }, {
    path: '/page2',
    meta: {
      auth: true,
      title: '测试页2',
    },
    redirect: '/page2/index',
    name: 'page2',
    component: () => import('../views/Page2.vue'),
    children: [{
      path: '/page2/index',
      meta: {
        auth: true,
        keepAlive: true,
        title: '测试2主页'
      },
      name: 'page2Index',
      component: () => import('../views/Page2Index.vue'),
    }, {
      path: '/page2/:id',
      meta: {
        auth: true,
        title: '测试2详情'
      },
      name: 'page2Detail',
      component: () => import('../views/Page2Detail.vue'),
    }]
  }, {
    path: '/login',
    name: 'login',
    component: () => import('../views/Login.vue')
  }, {
    path: '/:catchAll(.*)',
    // :pathMatch(.*)*
    meta: {
      title: '页面丢失'
    },
    name: 'notfound',
    component: () => import('../views/NotFound.vue')
  }]
})

Router.beforeEach((to, from, next) => {
  // console.log(to);
  // console.log(from);
  NProgress.start();

  let session = utils.getlocalStorage('userInfo') || {}
  if (to.meta.auth) {
    if (session && session.sessionid) {
      if (to.name == 'login') {
        next(false)
      } else {
        next()
      }
    } else {
      next('/login')
    }
  } else {
    if (session && session.sessionid) {
      if (to.name == 'login') {
        next('/')
      } else {
        next()
      }
    } else {
      next()
    }
  }
})
Router.afterEach((to, from) => {
  // console.log(to);
  // console.log(from);
  NProgress.done();
})

export default Router
